﻿using System.IO;
using System.Runtime.Serialization;
using System.Text;
using System.Xml;
using Microsoft.Xrm.Sdk;
using SolutionExtender.Interfaces;

namespace McTools.SolutionExtender.ParametersPlugin
{
    public class ParameterConnector : IConnector
    {
        #region Variables

        /// <summary>
        /// IOrganization service to access CRM 2011 data
        /// </summary>
        private readonly IOrganizationService _service;

        #endregion Variables

        #region Constructor

        /// <summary>
        /// Initializes a new instance of class ParameterConnector
        /// </summary>
        /// <param name="service">IOrganization service to access CRM 2011 data</param>
        public ParameterConnector(IOrganizationService service)
        {
            _service = service;
        }

        #endregion Constructor

        #region Properties

        public string ObjectName
        {
            get { return "Parameter"; }
        }

        public string Description
        {
            get { return "Allows to export parameter from MsCrmTools parameters."; }
        }

        #endregion Properties

        #region Methods

        public void Import(XmlNode data)
        {
            foreach (XmlNode buNode in data.ChildNodes)
            {
                Entity record;

                var memoryStream = new MemoryStream(Encoding.UTF8.GetBytes(buNode.OuterXml));

                using (var reader = XmlDictionaryReader.CreateTextReader(memoryStream, Encoding.UTF8,
                                                                         new XmlDictionaryReaderQuotas(), null))
                {

                    var serializer = new DataContractSerializer(typeof(Entity),
                                                                null,
                                                                int.MaxValue,
                                                                false,
                                                                false,
                                                                null,
                                                                new KnownTypesResolver());

                    record = (Entity)serializer.ReadObject(reader);
                }

                _service.Create(record);
            }
        }

        public IExportControl GetExportControl(IOrganizationService service)
        {
            return new ParameterControl(_service);
        }

        public string GetRecordName(XmlNode node)
        {
            return node.Attributes["name"].Value;
        }

        #endregion Methods
    }
}
